
from datetime import datetime
import json
from time import sleep

from config import (
    MASTER_ACCOUNTS_QUALITY,
    REFERRAL_ACCOUNTS_QUALITY,
    CREATE_ACCOUNT_ROUNDS,
    MAIL_SUBJECT,
    MAIL_FROM,
)
from log import logger
from utils import (
    get_email,
    get_proxy,
    get_user_agent,
    get_wallet,
)
from steps import *


from requests.packages.urllib3 import disable_warnings
from requests.packages.urllib3.exceptions import InsecureRequestWarning

disable_warnings(InsecureRequestWarning)


def create_account(number, referral_code):

    account_data = {
        'uuid': None,
        'referral_code': referral_code,
        'email': get_email(),
        'proxy': get_proxy(number),
        'user_agent': get_user_agent(),
        'wallet': get_wallet(),
        'create_date': str(datetime.now())
    }

    get_recaptcha_response_result = get_recaptcha_response()
    if get_recaptcha_response_result['status'] != 'success':
        logger.error('code: BDT2x3fX96emgA5U')
        return {'status': 'error'}

    set_user_result = set_user(
        email=account_data['email'],
        wallet_address=account_data['wallet']['address'],
        referral_code=referral_code,
        recaptcha_response=get_recaptcha_response_result['data']['recaptcha_response'],
        proxies=account_data['proxy']['proxies'],
        user_agent=account_data['user_agent']
    )
    if set_user_result['status'] != 'success':
        logger.error('code: 26S53JXve3YS2sAv')
        return {'status': 'error'}
    account_data['uuid'] = set_user_result['data']['uuid']
    logger.debug(set_user_result)

    verification_email_result = verification_email(
        email=account_data['email'],
        _from=MAIL_FROM,
        subject=MAIL_SUBJECT,
        proxies=account_data['proxy']['proxies'],
        user_agent=account_data['user_agent']
    )
    if verification_email_result['status'] != 'success':
        logger.error('code: Y8YVBzxLWu3RgHnk')
        return {'status': 'error'}
    logger.debug(verification_email_result)

    write_account_data(referral_code, account_data)
    print(json.dumps(account_data, indent=4))

    return {
        'status': 'success',
        'data': account_data
    }


def account_handler(number, referral_code):
    for i in range(CREATE_ACCOUNT_ROUNDS):
        try:
            sleep(5)
            create_account_resutl = create_account(number, referral_code)
            if create_account_resutl['status'] != 'success':
                logger.error(f'Неудачная попытка создания аккаунта {number}.')
                continue
            logger.info(f'Аккаунт {number} успешно создан!')
            return create_account_resutl
            break
        except Exception as e:
            logger.error(e)
    return {'status': 'error'}


def main():

    number = 0

    for master_account_number in range(1, MASTER_ACCOUNTS_QUALITY+1):
        logger.info('\nНачинаю создание аккаунта реферавода..')
        account_handler_result = account_handler(number, '')
        number += 1
        if account_handler_result['status'] != 'success':
            sleep(66)
            continue
        referral_code = account_handler_result['data']['uuid']
        for referral_account_number in range(1, REFERRAL_ACCOUNTS_QUALITY+1):
            logger.info(f'\nНачинаю создание аккаунта реферала к {referral_code}..')
            account_handler_result = account_handler(number, referral_code)
            number += 1
            if account_handler_result['status'] != 'success':
                sleep(66)
                continue


if __name__ == '__main__':
    main()
